const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const moment = require('moment')
const checkType = require('../utils/checkType')
const crypto = require('crypto')

router
    .post('/', async(req, res) => {
        const {body: {maddr, pwd,deviceNo,deviceName,platform}} = req
        logI("A-S", maddr, "login", `${JSON.stringify(req.body)}`, "null")
        try {
            const error = checkType.login(req.body)
            if(error){
                retError("login", maddr,10001,  error.details[0].message, res);
            }else{
                const updateTime = moment().format('YYYY-MM-DD HH:mm:ss')
                await userDb.updateVerify(1,updateTime,maddr);
                let data = {};
                data = await userDb.mailExist(maddr);
                if(data){
                    if(data.verify === 0){
                        retError("login", maddr,10007, "user does not exist", res);
                    }else{
                        const hashPass = crypto.createHmac('sha256', process.env.APP_SECRET)
                            .update(pwd)
                            .digest('hex')
                        if(data.pwd === hashPass){
                            const time = moment().format('YYYY-MM-DD HH:mm:ss');
                            userDb.updateDeviceInfo(maddr,time,deviceNo,deviceName,platform,time,deviceName,platform);
                            const msg = {
                                "token": data.token,
                                "name":data.name,
                                "createTime":moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
                            }
                            retSuccess("login", maddr,0, msg, res);

                        }else{
                            retError("login", maddr,10009, "username or password incorrect", res);
                        }
                    }
                }else{
                    retError("login", maddr,10007, "user does not exist", res);
                }
            }
        } catch (e) {
            retError("login", maddr,10001, e, res);
        }
    })

module.exports = router
